﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HappyLine.Properties;
using XCoolForm;
using IWshRuntimeLibrary;
using System.IO;

namespace HappyLine
{

    public partial class MainForm : XCoolForm.XCoolForm
    {
        private XmlThemeLoader xtl = new XmlThemeLoader();
        Size actualSize;
        Point actualPoint;
        List<LineData> HappyLines = new List<LineData>();
        public MainForm()
        {
            InitializeComponent();
            actualSize = this.Size;
            
        }
        XCoolForm.XStatusBar.XBarItem processing_bar = new XCoolForm.XStatusBar.XBarItem(60, "Done");
        XCoolForm.XTitleBarIconHolder.XHolderButton edit_lines_button = new XCoolForm.XTitleBarIconHolder.XHolderButton(Resource.duck_48x48.GetThumbnailImage(20, 20, null, IntPtr.Zero), "Edit lines", "Edit lines");
        XCoolForm.XTitleBarIconHolder.XHolderButton author_button = new XCoolForm.XTitleBarIconHolder.XHolderButton(Resource.Bear_48.GetThumbnailImage(20, 20, null, IntPtr.Zero), "About","Author info");
        private void Form1_Load(object sender, EventArgs e)
        {
            #region Theme init
            this.Border.BorderStyle = XCoolForm.X3DBorderPrimitive.XBorderStyle.X3D;
            this.TitleBar.TitleBarType = XCoolForm.XTitleBar.XTitleBarType.Rectangular;
            this.TitleBar.TitleBarCaption = "Happy Line for Kate :-*";

            this.TitleBar.TitleBarFill = XCoolForm.XTitleBar.XTitleBarFill.LinearRendering;

            this.TitleBar.TitleBarBackImage = Resource.paisley_6_48x48;
            this.StatusBar.EllipticalGlow = false;

            this.StatusBar.BarBackImage = Resource.Dino_orange_48x48;
            this.StatusBar.BarImageAlign = XCoolForm.XStatusBar.XStatusBarBackImageAlign.Center;
            this.StatusBar.BarItems.Add(new XCoolForm.XStatusBar.XBarItem(60));
            this.StatusBar.BarItems.Add(new XCoolForm.XStatusBar.XBarItem(150, ""));
            this.StatusBar.BarItems.Add(processing_bar);
            this.StatusBar.BarItems[1].BarItemText = "Happy lines count: 0";
            this.MenuIcon = Resource.purple_flower_48x48.GetThumbnailImage(30, 30, null, IntPtr.Zero);
           
            this.IconHolder.HolderButtons.Add(edit_lines_button);
            this.XCoolFormHolderButtonClick += new XCoolFormHolderButtonClickHandler(MainForm_XCoolFormHolderButtonClick);
            this.IconHolder.HolderButtons.Add(author_button);
            xtl.ThemeForm = this;
            xtl.ApplyTheme(Application.StartupPath + @"\Themes\ValentineTheme.xml");
            #endregion
            #region MainInit
            textBoxLineServiceUrl.Text = "http://line.mole.ru/metoyou/";
            buttonChangeServiceUrl_Click(this, null);
            autorunToolStripMenuItem.Checked = System.IO.File.Exists(String.Format("{0}\\HappyLine.lnk",Application.StartupPath));
            LoadParams();
            this.TopMost = true;
           
            this.StatusBar.BarItems[1].BarItemText = String.Format("Happy lines count: {0}", HappyLines.Count);
            #endregion
        }
        void EditOperations() 
        {
            if (HappyLines.Count == 0)
            {
                MessageBox.Show("Happy line list is empty.", "Heh", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            EditForm ef = new EditForm(HappyLines);
            ef.ShowDialog();
            this.StatusBar.BarItems[1].BarItemText = String.Format("Happy lines count: {0}", HappyLines.Count);
            if (ef.res != null) 
            {
                textBoxLineName.Text = ef.res.Name;
                textBoxLineUrl.Text = ef.res.Url;
            }
        }
        void MainForm_XCoolFormHolderButtonClick(XCoolForm.XCoolForm.XCoolFormHolderButtonClickArgs e)
        {
            if (e.ButtonIndex == 0) 
            {
                EditOperations();

            }
            if (e.ButtonIndex == 1) 
            {
                MessageBox.Show("Programmed by Yury Revotyuk (c) 2009", "About", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

      

        private void Form1_Resize(object sender, EventArgs e)
        {

            if (WindowState != FormWindowState.Minimized)
            {//this.Size = actualSize;
                foreach (Control ctrl in this.Controls)
                {
                    if (ctrl is GroupBox)
                        continue;
                    if (ctrl.Top > groupBox1.Top)
                        ctrl.Top += this.Height - actualSize.Height;
                    ctrl.Left += this.Width - actualSize.Width;
                }
                //groupBox1.Height = this.Height - 176;
                //groupBox1.Width = this.Width - 29;
                groupBox1.Height += this.Height - actualSize.Height;
                groupBox1.Width += this.Width - actualSize.Width;
                actualSize = this.Size;
                
            }
            else
            {
                this.Visible = false;
                
            }
        }

        private void buttonChangeServiceUrl_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(textBoxLineServiceUrl.Text))
            {
                MessageBox.Show("Please enter service url", "Ups...((", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (!textBoxLineServiceUrl.Text.StartsWith("http://"))
                textBoxLineServiceUrl.Text = "http://" + textBoxLineServiceUrl.Text;
            try
            {
                webBrowser1.Navigate(textBoxLineServiceUrl.Text);
            }
            catch 
            {
                MessageBox.Show("Some troubles while connect to line service. Check internet connection and url", "Ups...((",MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            textBoxLineServiceUrl.Text = webBrowser1.Url.ToString();
        }

        private void buttonAddLine_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(textBoxLineUrl.Text))
            {
                MessageBox.Show("Please enter line image url", "Ups...((", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (String.IsNullOrEmpty(textBoxLineName.Text))
            {
                MessageBox.Show("Please enter happy line name", "Hum...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            LineData ld = HappyLines.Find(x => String.Compare(x.Name, textBoxLineName.Text, true) == 0);
            if (ld != null) 
            {
                MessageBox.Show("Please enter other happy line name", "Hum...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!textBoxLineUrl.Text.StartsWith("http://"))
                textBoxLineUrl.Text = "http://" + textBoxLineUrl.Text;
            LineForm lf = new LineForm();
            lf.HappyLineStateChanged += new HappyLineHandler(lf_HappyLineStateChanged);
            if (!lf.InitLine(textBoxLineName.Text,textBoxLineUrl.Text))
            {
                MessageBox.Show("Some troubles while loading happy line. Check internet connection and url", "Ups...((", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            HappyLines.Add(new LineData()
            {
                LineForm = lf,
                Name = textBoxLineName.Text,
                Url = textBoxLineUrl.Text
            });
            this.StatusBar.BarItems[1].BarItemText = String.Format("Happy lines count: {0}", HappyLines.Count);
            lf.Show();
           
           
        }

        private void lf_HappyLineStateChanged(object sender, HappyLineState hls)
        {
            switch (hls) 
            {
                case HappyLineState.DELETED:
                    HappyLines.RemoveAll(x => x.Name == ((LineForm)sender).LineName);
                    break;
                case HappyLineState.LOADED:
                    this.processing_bar.BarItemText = "Done";
                    break;
                case HappyLineState.ERROR:
                    //HappyLines.RemoveAll(x => x.Name == ((LineForm)sender).LineName);
                    break;
                case HappyLineState.LOADING:
                    this.processing_bar.BarItemText = String.Format("Loading ...{0}",((LineForm)sender).LineName);
                    break;

            }
            this.StatusBar.BarItems[1].BarItemText = String.Format("Happy lines count: {0}", HappyLines.Count);
        }
        
        string SystemPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Startup) + @"\";//@"c:\Documents and Settings\All Users\Start Menu\Programs\Startup\";
        
        void SetAutorun() 
        {
            if (System.IO.File.Exists(String.Format("{0}\\HappyLine.lnk", SystemPath)))
            {
                System.IO.File.Delete(String.Format("{0}\\HappyLine.lnk", SystemPath));
            }

            
            try
            {
                WshShellClass wshShell = new WshShellClass();

                IWshShortcut MyShortcut;

                MyShortcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(String.Format("{0}\\HappyLine.lnk", SystemPath));
                MyShortcut.TargetPath = Application.ExecutablePath;
                MyShortcut.Description = "Happy Lines 1.0.1";
                MyShortcut.IconLocation = Application.StartupPath + @"\app.ico";
                MyShortcut.Save();

            }
            catch
            {
                autorunToolStripMenuItem.Checked = false;
            }
        }

        private void autorunToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (autorunToolStripMenuItem.Checked)
                SetAutorun();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void toolStripMenuItemShow_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            foreach (LineData ld in HappyLines)
            {
                ld.LineForm.Show();
                ld.LineForm.WindowState = FormWindowState.Normal;
            }
            
        }

        private void SaveParams() 
        {
            try
            {
                using (StreamWriter sw = new StreamWriter("params.bin"))
                {
                    foreach (LineData ld in HappyLines) 
                    { 
                        if(ld.LineForm == null)
                            continue;
                        string data = String.Format("{0}|{1}|{2}|{3}", ld.Name, ld.Url, ld.LineForm.Left, ld.LineForm.Top);
                        sw.WriteLine(data);
                    }
                }
            }
            catch
            { }
        }
        private void LoadParams() 
        {
            if(!System.IO.File.Exists("params.bin"))
                return;
            try{
            using (StreamReader sr = new StreamReader("params.bin")) 
            {
                while (sr.Peek() >= 0) 
                {
                    string data = sr.ReadLine();
                    string[] sp = data.Split('|');
                    if (sp.Length < 4)
                        continue;
                    
                    LineForm lf = new LineForm();
                    lf.HappyLineStateChanged += new HappyLineHandler(lf_HappyLineStateChanged);
                    lf.InitLine(sp[0], sp[1]);
                    
                    HappyLines.Add(new LineData()
                    {
                        LineForm = lf,
                        Name = sp[0],
                        Url = sp[1]
                    });
                    lf.SetPlacement(int.Parse(sp[2]),int.Parse(sp[3]));
                    lf.Show();
                }
            }
            }catch
            {}
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveParams();
        }

        private void toolStripMenuItemHappyLines_Click(object sender, EventArgs e)
        {
            foreach (LineData ld in HappyLines)
            {
                ld.LineForm.Show();
                ld.LineForm.WindowState = FormWindowState.Normal;
            }
            EditOperations();
        }

        private void notifyIconMain_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            foreach (LineData ld in HappyLines)
            {
                ld.LineForm.Visible = true;
                ld.LineForm.WindowState = FormWindowState.Normal;
            }
           // this.Hide();
        }
        
    }

   
    public class LineData
    {
        public string Name;
        public string Url;
        public LineForm LineForm;
    }
}
